package com.csnf.controller;

import com.csnf.config.MinioConfig;
import com.csnf.dto.ResponseObject;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UploadController {
    private final MinioConfig minioConfig;

    public UploadController(MinioConfig minioConfig) {
        this.minioConfig = minioConfig;
    }

    @RequestMapping("/uploadusertouxiang")
    public ResponseObject uploadUserTouxiang(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseObject.error("文件为空", 400);
        } else {
            try {
                String uuid = UUID.randomUUID().toString();
                String objectName = uuid + ".jpg";
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(file.getBytes());
                minioConfig.minioClient().putObject(
                        PutObjectArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .object(objectName)
                                .stream(byteArrayInputStream, file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build()
                );
                return ResponseObject.success(objectName,200);
            } catch (IOException | ErrorResponseException | InsufficientDataException | InternalException |
                     InvalidKeyException | InvalidResponseException | NoSuchAlgorithmException | ServerException |
                     XmlParserException e) {
                e.printStackTrace();
                return ResponseObject.error("上传失败"+e.getMessage(),500);
            }
        }
    }
}
